import datetime as datetime
import sys
import os
sys.path.append('C:/Project/Python3')
sys.path.append('D:/Project/Python3')
import Core.WindFunctions as Wind
import Core.Config as Config

from DataProcess.Download_Stock_List import Download_Stock_List
from DataProcess.DownloadFutureData import Download_Future_List
from DataProcess.Download_MutualFund_Data import Download_MutualFund_List
from DataProcess.General import Download_DailyBars
from DataProcess.General import Automatic_Download_DailyQuote
from DataProcess.Download_MutualFund_Report import Batch_Download_MutualFund_Reports, Automatic_Download_MutualFund_Reports


def download_mutualfund_daily_bars(database, datetime1, datetime2, start_index=0):

    instruments = database.Find("financial_data", "instrument_mutualfund")
    i = 0
    for instrument in instruments:
        i += 1
        symbol = instrument["symbol"]
        begin_datetime = instrument["datetime1"]  # 上市时间
        end_datetime = instrument["datetime2"]  # 退市时间
        #
        if begin_datetime < datetime1:
            begin_datetime = datetime1
        if end_datetime > datetime2:
            end_datetime = datetime2
        #
        print("Download_DailyBars", i, begin_datetime, end_datetime)
        #
        Download_DailyBars(database,
                           symbol,
                           instrument_type="MutualFund",
                           begin_datetime=begin_datetime,
                           end_datetime=end_datetime,
                           logger=None,
                           save=False)
        a = 0


if __name__ == '__main__':

    # ---Connecting Database---
    path_filename = os.getcwd() + "\..\Config\config_local.json"
    database = Config.create_database(database_type="MySQL", config_file=path_filename, config_field="MySQL")

    # ---Start Wind API---
    Wind.w.start()

    # ---更新公募基金信息和下市信息---
    # Download_MutualFund_List(database, force_to_update=True)

    # ---公募基金行情相数据---
    # ---区间数据下载---
    datetime1 = datetime.datetime(2020, 12, 26)
    datetime2 = datetime.datetime(2021, 6, 14)
    download_mutualfund_daily_bars(database, datetime1, datetime2, start_index=0)

    # ---尾部数据自动更新---
    # end_datetime = datetime.datetime(2021, 6, 1)
    # Automatic_Download_DailyQuote(database, end_datetime, instrument_type="MutualFund", start_index=0, config=None)

    # ---更新 公募基金季度报告（含持仓信息）---
    reportDate = datetime.datetime(2020, 9, 30)
    Automatic_Download_MutualFund_Reports(database, reportDate, startIndex=0)  # 001825.OF
    # Fix_MutualFund_Positions(database, reportDate, reportDate, start_index=0) # 27137

    # ---基金报告冷启动（第一次建立数据库）---
    # datetime1 = datetime.datetime(1991, 1, 1)
    # datetime2 = datetime.datetime(2020, 11, 1)
    # Batch_Download_MutualFund_Reports(database, instruments, datetime1, datetime2, True)

